﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using Common.Model;
using Common.PddApi;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;
using pinduoduo.From;
using Utils;
using System.Threading;
using Common.Service;
using Common.Util;
using RestSharp;
using System.Dynamic;

namespace pinduoduo.Page
{
    public partial class MainPage : UIPage
    {
        private string activityID;
        public PddToken AccountPddToken { get; set; }
        public RequestContext AccountContext { get; set; }
        private List<ListItem> SkuList = new List<ListItem>();
        private List<ListItemString> CouponList = new List<ListItemString>();
        
        private IEnumerable<AreaModel> areaModelList = new List<AreaModel>();

        private readonly string pddurl = "http://yangkeduo.com/";

        private List<string> gIdList = new List<string>();
        private double CurServerTime = SystemUtil.GetTimeStamp();
        private IList<PddToken> pddTokens = new List<PddToken>();

        private PddTokenService pddTokenService = new PddTokenService();
        private IEnumerable<PddAddressDBModel> pddAddressDBModelList = new List<PddAddressDBModel>();

        private Main mainForm;

        private bool StartTask = false;
        private bool StopTask = false;

        public MainPage(Main mainForm)
        {
            this.mainForm = mainForm;

            InitializeComponent();



            InitGoodIdData();

            InitToken();

            UpdateAddressList();
            areaModelList = DataBaseHelper.SqLiteDBCon.GetAll<AreaModel>();

            uiToolTip1.SetToolTip(uiSymbolLabel1, "自动支付是模拟鼠标键盘输入\n自动执行过程中请不要操作电脑\n如果不想自动输入密码可不填哦\n如果检测失败，请手动关闭窗口，任务继续进行",
    "自动支付说明", 61530, 32, UIColor.Green);

            uiToolTip1.SetToolTip(qudongPayCheckBox, "如果插件不好使，请使用传统模式\n 插件可以不占用鼠标键盘\n传统模式是模拟键盘鼠标的");
            string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\pay.tmp";
            if (File.Exists(path))
            {
                this.PayPassword.Text = File.ReadAllText(path);
                Global.Global.PayPassword = this.PayPassword.Text;
            }

            InitConfig();
        }

        public void UpdateAddressList()
        {

           var DBpddAddressModelList = DataBaseHelper.SqLiteDBCon.GetAll<PddAddressDBModel>();

            List<PddAddressDBModel> pddAddressDBModels = new List<PddAddressDBModel>();
            if (!string.IsNullOrWhiteSpace(Global.Global.Province))
            {
                string[] provinceArr = Global.Global.Province.Split(" ");
                foreach (var pddAddressDB in DBpddAddressModelList)
                {
                    foreach (var province in provinceArr)
                    {
                        if (pddAddressDB.address.StartsWith(province))
                        {
                            //pddAddressDBModelList.ToList().Add(pddAddressDB);
                            pddAddressDBModels.Add(pddAddressDB);

                        }
                    }

                }
                pddAddressDBModelList = pddAddressDBModels;
            }
            else {
                pddAddressDBModelList = DBpddAddressModelList;
            }
         
        }

      
        private void InitConfig()
        {
            string dailiUrl = IniHelper.GetPrivateProfileString("STARTUP", "dailiUrl", IniHelper.IniPathFile, 500);
            string isSetDaili = IniHelper.GetPrivateProfileString("STARTUP", "isSetDaili", IniHelper.IniPathFile, 500);
            string PayModeStr = IniHelper.GetPrivateProfileString("STARTUP", "PayMode", IniHelper.IniPathFile, 500);
           
            this.GetIpUrl.Text = dailiUrl;

            bool paymode;
            bool.TryParse(PayModeStr,out paymode );
            this.qudongPayCheckBox.Checked = paymode;

            if (isSetDaili == "true")
            {
                this.yuiipRadioButton.Checked = false;
            }
            else 
            {
                this.yuiipRadioButton.Checked = true;
            }
        }


        async void InitToken()
        {
            AccountContext = CefUtils.GetAccountContext();
            await CefUtils.GetAccountContext().GetCookieManager(null).FlushStoreAsync();

            List<CefSharp.Cookie> cookies2 = await AccountContext.GetCookieManager(null).VisitUrlCookiesAsync("http://mobile.yangkeduo.com", true);
            List<CefSharp.Cookie> cookies = await AccountContext.GetCookieManager(null).VisitAllCookiesAsync();
            if (cookies == null || cookies.Count == 0)
            {
                if(ShowAskDialog("请先登录拼多多大号， 大号主要是获取商品信息的"))
                {
                    mainForm.SelectPage(1);
                }
                return;
            }

            CefSharp.Cookie PDDAccessTokenCookie = cookies.Where(x => { return x.Name == "PDDAccessToken"; }).FirstOrDefault();
            CefSharp.Cookie pdd_user_id_cookie = cookies.Where(x => { return x.Name == "pdd_user_id"; }).FirstOrDefault();
            if (PDDAccessTokenCookie == null || pdd_user_id_cookie == null)
            {
                if (ShowAskDialog("请先登录拼多多大号， 大号主要是获取商品信息的"))
                {
                    mainForm.SelectPage(1);
                }
                return;
            }
            PddToken pddToken = new PddToken();
            pddToken.PDDAccessToken = PDDAccessTokenCookie.Value;
            pddToken.pdd_user_id = pdd_user_id_cookie.Value;
            pddToken.account_type = 1;

            AccountPddToken = pddToken;
        }

        private void InitGoodIdData()
        {
            var pddGoods = DataBaseHelper.SqLiteDBCon.GetAll<PddGood>();

            foreach (var item in pddGoods)
            {
                this.GoodComboBox.Items.Add(item.good_id);
            }
        }
      
 
       
        /// <summary>
        /// 从网络抓取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void GetNetGoodButton_Click(object sender, EventArgs e)
        {
            if (AccountPddToken == null)
            {

                ShowErrorDialog("请先登陆主账号");
                return;
            }

            PddGood pddGood = null;

            //if (this.PiFaRadioButton.Checked)
            //{
            //    string url = "https://pifa.pinduoduo.com/goods/detail/?gid=" + GetGoodId();
            //    BrowserFrom browserFrom = new BrowserFrom();
            //    browserFrom.action = UpdateGoodInfo;
            //    browserFrom.LoadUrl(url, 5000);
            //    browserFrom.ShowDialog();

            //    return;
            //}
            if (this.DuoDuoRadioButton.Checked)
            {
                if (GetGoodId().StartsWith("https://p.pinduoduo.com/"))
                {
                    string url = GetGoodId();

                    //BrowserFrom browserFrom = new BrowserFrom();
                    //browserFrom.action = UpdateGoodInfo;
                    //browserFrom.SetGoodIdAction = SetGoodId;
                    //browserFrom.LoadUrl(url, 5000, (int)PddGoodSource.DuoDuo);
                    //browserFrom.ShowDialog();
                    BrowserNewFrom browserNewFrom = new BrowserNewFrom(url, AccountPddToken,PddGoodSource.DuoDuo);
                    browserNewFrom.UpdateGoodInfoAction = UpdateGoodInfo;
                    browserNewFrom.SetGoodIdAction = SetGoodId;
                    browserNewFrom.ShowDialog();
                    return;
                }
                else
                {
                    ShowErrorDialog("请输入多多链接");
                    return;
                }
            }

            if (this.ZhiBoRadioButton.Checked) {
                if (GetGoodId().StartsWith("https://mobile.yangkeduo.com/"))
                {
                    string url = GetGoodId();

                    BrowserNewFrom browserNewFrom = new BrowserNewFrom(url, AccountPddToken);
                    browserNewFrom.UpdateGoodInfoAction = UpdateGoodInfo;
                    browserNewFrom.SetGoodIdAction = SetGoodId;
                    browserNewFrom.ShowDialog();
                    return;
                }
                else
                {
                    ShowErrorDialog("请输入直播链接");
                    return;
                }
            }


            RestSharp.IRestResponse response;
            if (this.pinNeiGouRadioButton.Checked)
            {
                PinNeigou pinNeigou = new PinNeigou();
                pinNeigou.goods_id = GetGoodId();

                string urlAnti = "https://api.pinduoduo.com/api/brand-philips-trade/goods/detail/v2";
                string ant = FackUtil.GetAnti(null, urlAnti);

                pinNeigou.anti_content = ant;
                response = await PddApi.GetPinNeigouGoodInfo(pinNeigou, AccountPddToken);
            }
            else 
            {
                response = await PddApi.GetGoodInfo(GetGoodId(), AccountPddToken);
            }

            if (string.IsNullOrWhiteSpace(response.Content))
            {
                ShowErrorDialog("获取数据为空！接口有问题啦");
                return;
            }

            if (response.Content.Contains("请登录后再操作"))
            {
                ShowErrorDialog("获取方式异常，可能是账号失效，如果账号正常，获取失败，请换种方式获取");
                return;
            }

            if (response.Content.Contains("verify_auth_token")
               && response.Content.Contains("error_code"))
            {
                ShowErrorDialog("请去主账号里输入验证码");
                return;
            }

            if (response.Content.Contains("verify_auth_token")
              && response.Content.Contains("error_code"))
            {
                ShowErrorDialog("请输入验证码");
                return;
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                ShowErrorDialog("获取失败，请检查主号是否有异常");
                return;
            }

            if (this.pinNeiGouRadioButton.Checked)
            {
                pddGood = PaserPinNeiGouGoogInfo(response, GetGoodId());
            }
            else 
            {
                pddGood = PddApi.PaserGoogInfo(response, GetGoodId());
            }

                

            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(GetGoodId());

            SetGoodInfo(pdd);
            this.SourceTextBox.Text = pdd.SourceKeywords;
        }

        private PddGood PaserPinNeiGouGoogInfo(RestSharp.IRestResponse res, string v)
        {
            JObject jo = JObject.Parse(res.Content);
       
            PddGood pddGood = new PddGood();

            dynamic groupObj = jo["result"]["group"];
            string goods_id = jo["result"]["goods_id"].ToString();
            pddGood.gID2 = groupObj[0]["group_id"] + "";
            pddGood.gID1 = groupObj[1]["group_id"] + "";
            var mkt_domain = jo["result"]["mkt"]["mkt_domain"].ToString();
            var mkt_tr_sc = jo["result"]["mkt"]["mkt_tr_sc"].ToString();
            var mkt_tr_token = jo["result"]["mkt"]["mkt_tr_token"].ToString();
            var biz_sn = jo["result"]["biz_extra"]["mall_info"]?["biz_sn"]?.ToString();
             

            dynamic skuObj = jo["result"]["sku_list"];
            var mall_id = jo["result"]["mall_id"].ToString();

            pddGood.type = (int)PddGoodSource.PinNeiGou;

            pddGood.good_id = goods_id;
            pddGood.mkt_domain = mkt_domain;
            pddGood.mkt_tr_sc = mkt_tr_sc;
            pddGood.mkt_tr_token = mkt_tr_token;
            pddGood.mall_id = mall_id;
            pddGood.biz_sn = biz_sn;

            if (skuObj != null)
            {
                string skuJson = JsonHelper.SerializeObject(skuObj);
                pddGood.sku = skuJson;
            }

            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(pddGood.good_id);
            if (pdd == null)
            {
                long reslut = DataBaseHelper.SqLiteDBCon.Insert<PddGood>(pddGood);
            }
            else
            {
                pddGood.SourceKeywords = pdd.SourceKeywords;
                DataBaseHelper.SqLiteDBCon.Update<PddGood>(pddGood);
            }
           
            return pdd;
        }

        /// <summary>
        /// 从本地抓取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetDbButton_Click(object sender, EventArgs e)
        {
            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(GetGoodId());
            if (pdd != null)
            {
                SetGoodInfo(pdd);
                this.SourceTextBox.Text = pdd.SourceKeywords;
            }
        }

        private void SetGoodInfo(PddGood pdd)
        {
            if (pdd == null)
            {
                ShowErrorDialog("请先本地获取！");
                return;
            }

            this.SkuList.Clear();
            gIdList.Clear();
            CouponList.Clear();
            activityID = "";


            if (pdd.type == (int)PddGoodSource.ZhiBo)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);

                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                //activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuId;
                    string normalPriceStr = item.normalPrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.specs;

                    StringBuilder spec_value =new StringBuilder();
                    foreach (dynamic spec in specs)
                    {
                        spec_value.Append(spec.spec_key);
                        spec_value.Append(":");
                        spec_value.Append(spec.spec_value);
                        spec_value.Append(";");
                    }

                    try
                    {

                        //string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString();
                        //string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString();
                        string text = "拼单:" + groupPriceStr + " 元" + "单买:" + normalPriceStr + "元 " + spec_value.ToString();

                        //string text = "拼单:" + groupPriceStr + " 元" + "批发:" + normalPriceStr + "元 " + spec_value;
                        SkuList.Add(new ListItem(skuId, text));
                    }
                    catch { }

                }
            }


            if (pdd.type == (int)PddGoodSource.PinNeiGou)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);

                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                //activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.sku_id;
                    string normalPriceStr = item.normal_price;
                    string groupPriceStr = item.group_price;
                    dynamic specs = item.specs;

                    StringBuilder spec_value = new StringBuilder();
                    foreach (dynamic spec in specs)
                    {
                        spec_value.Append(spec.spec_key);
                        spec_value.Append(":");
                        spec_value.Append(spec.spec_value);
                        spec_value.Append(";");
                    }

                    try
                    {

                        string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString() ;
                        string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString();
                        string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value.ToString();

                        //string text = "拼单:" + groupPriceStr + " 元" + "批发:" + normalPriceStr + "元 " + spec_value;
                        SkuList.Add(new ListItem(skuId, text));
                    }
                    catch { }

                }
            }

            if (pdd.type == (int)PddGoodSource.DuoDuo)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);
                
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;

                if (!string.IsNullOrWhiteSpace(pdd.coupon_list))
                {

                    dynamic coupon_list = JArray.Parse(pdd.coupon_list);
                    foreach (var item in coupon_list)
                    {
                        string batch_sn="";
                        string batch_copy_writing = "";
                        var isExist =   IsPropertyExist(item, "batch_sn");
                        if (isExist) {
                            batch_sn = item["batch_sn"].ToString();
                            batch_copy_writing = item["batch_copy_writing"].ToString();
                        }

                        if(IsPropertyExist(item, "batchSn")){
                            batch_sn = item["batchSn"].ToString();
                            batch_copy_writing = item["batchCopyWriting"].ToString();
                        }
                     

                        CouponList.Add(new ListItemString(batch_sn, batch_copy_writing));
                    }

                }

                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuID;
                    string normalPriceStr = item.normalPrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.specs;


                    StringBuilder spec_value = new StringBuilder();
                    foreach (dynamic spec in specs)
                    {
                        spec_value.Append(spec.spec_key);
                        spec_value.Append(":");
                        spec_value.Append(spec.spec_value);
                        spec_value.Append(";");
                    }


                    try
                    {
                        string text = "拼单:" + groupPriceStr + " 元" + "单买:" + normalPriceStr + "元 " + spec_value.ToString();
                        SkuList.Add(new ListItem(skuId, text));
                    }
                    catch { }

                }
            }

            if (pdd.type == (int)PddGoodSource.Pifa)
            {

                dynamic arrdata = JArray.Parse(pdd.sku);
                activityID = pdd.atvid;

                foreach (dynamic item in arrdata)
                {
                    double skuId = item.skuId;
                    string normalPriceStr = item.wholesalePrice;
                    string groupPriceStr = item.groupPrice;
                    dynamic specs = item.skuSpecs;
                
                    //string spec_value = "";
                    //foreach (dynamic spec in specs)
                    //{
                    //    spec_value = spec.specValue;
                    //}


                    StringBuilder spec_value = new StringBuilder();
                    foreach (dynamic spec in specs)
                    {
                        spec_value.Append(spec.specKey);
                        spec_value.Append(":");
                        spec_value.Append(spec.specValue);
                        spec_value.Append(";");
                    }

                    try
                    {
                        string groupPrice = Math.Round((decimal)(Convert.ToDouble(groupPriceStr) / Convert.ToDouble(100)), 2).ToString();
                        string normalPrice = Math.Round((decimal)(Convert.ToDouble(normalPriceStr) / Convert.ToDouble(100)), 2).ToString();
                        string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value.ToString();
                        SkuList.Add(new ListItem(skuId, text));
                    }
                    catch { }


                }

            }
            //从页面抓取的
            if (pdd.type == (int)PddGoodSource.PuTongHtml)
            {
                string sku = pdd.sku;
                var skuObj = JsonHelper.DeserializeObject<List<PddPageGood>>(sku);
               
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in skuObj)
                {
                    double skuId = item.skuId;
                    string normalPrice = item.normalPrice;
                    string groupPrice = item.groupPrice;
                    dynamic specs = item.specs;
                    double goodsId = item.goodsId;

                    StringBuilder spec_value = new StringBuilder();
                    foreach (dynamic spec in specs)
                    {
                        spec_value.Append(spec.spec_key);
                        spec_value.Append(":");
                        spec_value.Append(spec.spec_value);
                        spec_value.Append(";");
                    }
                    string text = "拼单:" + groupPrice + " 元" + "单买:" + normalPrice + "元 " + spec_value.ToString();
                    SkuList.Add(new ListItem(skuId, text));
                }
            }

            // 通过渲染界面 接口拿的数据
            if (pdd.type == (int)PddGoodSource.PuTong)
            {
                string sku = pdd.sku;

                dynamic arrdata = JArray.Parse(pdd.sku);
               
                gIdList.Add(pdd.gID2);
                gIdList.Add(pdd.gID1);
                activityID = pdd.atvid;
                foreach (dynamic item in arrdata)
                {
                    double skuId = item.sku_id;
                    string normalPrice = item.normal_price;
                    string groupPrice = item.group_price;
                    dynamic specs = item.specs;
                    double goodsId = item.goods_id;

                    StringBuilder spec_value = new StringBuilder();
                    foreach (dynamic spec in specs)
                    {
                        spec_value.Append(spec.spec_key);
                        spec_value.Append(":");
                        spec_value.Append(spec.spec_value);
                        spec_value.Append(";");
                    }
                    string text = "拼单:" + groupPrice.Insert(groupPrice.Length - 2, ".") + " 元" + "单买:" + normalPrice.Insert(normalPrice.Length - 2, ".") + "元 " + spec_value.ToString();
                    SkuList.Add(new ListItem(skuId, text));
                }
                if (!string.IsNullOrWhiteSpace(pdd.coupon_list)) {

                    dynamic coupon_list = JArray.Parse(pdd.coupon_list);
                    foreach (var item in coupon_list)
                    {
                        string batch_sn = item["batch_sn"].ToString();
                        string batch_copy_writing = item["batch_copy_writing"].ToString();

                        CouponList.Add(new ListItemString(batch_sn, batch_copy_writing));
                    }

                }
             
            }

            this.SkuComboBox.BeginInvoke(new Action(() =>
            {
                SkuComboBox.DataSource = null;
                SkuComboBox.DisplayMember = "Text";        //显示
                SkuComboBox.ValueMember = "Value";        //值
                SkuComboBox.DataSource = SkuList;
                if (SkuList.Count() > 0)
                {
                    SkuComboBox.SelectedIndex = 0;
                }
            }));

            this.CouponListComboBox.BeginInvoke(new Action(() =>
            {
                CouponListComboBox.DataSource = null;
                CouponListComboBox.DisplayMember = "Text";        //显示
                CouponListComboBox.ValueMember = "Value";        //值
                CouponListComboBox.DataSource = CouponList;
                if (CouponList.Count() > 0)
                {
                    CouponListComboBox.SelectedIndex = -1;
                }
            }));
        }

        private void SetGoodId(string goodId)
        {
            this.GoodComboBox.Text = goodId;
        }

        private void UpdateGoodInfo()
        {
            PddGood pdd = DataBaseHelper.SqLiteDBCon.Get<PddGood>(GetGoodId());
            if (pdd != null)
            {
                SetGoodInfo(pdd);
                this.SourceTextBox.Text = pdd.SourceKeywords;
            }
        }

        public static bool IsPropertyExist(dynamic data, string propertyname)
        {
            if (data is ExpandoObject)
                return ((IDictionary<string, object>)data).ContainsKey(propertyname);
            return data.GetType().GetProperty(propertyname) != null;
        }



        private async void StartPayButtonClick(object sender, EventArgs e)
        {
            if (StartTask) 
            {
                Msg("请等待任务完成", true);
                return;
            }
            StartTask = true;
            int startIndex = this.UserStartIndex.IntValue;
            int taskNum = this.TaskNum.IntValue;
            var tokens = pddTokenService.GetShuaDanToken();
            if (taskNum > tokens.Count() || startIndex > tokens.Count() || startIndex + taskNum - 1 > tokens.Count())
            {
                ShowErrorDialog("小号太少了，不能完成任务");
                StartTask = false;
                return;
            }

            PddToken pddToken = tokens.ElementAt(startIndex-1);
            if (pddToken == null)
            {
                ShowErrorDialog("请先选择一个小号");
                StartTask = false;
                return;
            }

            try
            {
                await SingBuyGood(pddToken, true);
            }
            catch (Exception e2)
            {
                LogHelper.Logger.Error("下单错误", e2);
            }
            Msg("任务完成");
            StartTask = false;
        }

        //public void UpdateOrderSn(PddToken pddTokenDb) 
        //{

        //    foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
        //    {
        //        var pddToken = dataGridViewRow.DataBoundItem as PddToken;
        //        if (pddTokenDb.pdd_user_id== pddToken.pdd_user_id)
        //        {
        //            pddToken.last_order_sn = pddTokenDb.last_order_sn;
        //            this.UserDataGridView.Refresh();
        //            break;
        //        }
        //    }
        //}

        private async Task<PayResult> SingBuyGood(PddToken pddToken,bool singBuy=false)
         {

            PddGood pddGood = DataBaseHelper.SqLiteDBCon.Get<PddGood>(GetGoodId());
            if (pddGood == null)
            {
                Msg("请先获取商品信息", true);
                return PayResult.No;
            }

            if (pddGood.SourceKeywords != this.SourceTextBox.Text)
            {
                pddGood.SourceKeywords = this.SourceTextBox.Text;
                await DataBaseHelper.SqLiteDBCon.UpdateAsync(pddGood);
            }
            if (this.SkuComboBox.SelectedValue == null) 
            {
                Msg("请选择商品SKU",true);
                return PayResult.No;
            }
            double skuIdStr = (double)this.SkuComboBox.SelectedValue;
            string coupon = this.CouponListComboBox.SelectedValue?.ToString();
            double goodsId = double.Parse(GetGoodId());


            if (this.PiFaRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.PuTong && pddGood.type != (int)PddGoodSource.PuTongHtml)
                {
                    Msg("请先获取商品信息,选择普通入口获取就可以", true);
                    return PayResult.No;
                }
                //if (pddGood.firstLadderStartValue == 0)
                //{
                //    Msg("请重新获取商品信息", true);
                //    return PayResult.No;
                //}
                if (this.SkuNumberIntegerTextBox.IntValue < 2)
                {
                    Msg("2件起购",true);
                    return PayResult.No;
                }
            }

            if (this.DuoDuoRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.DuoDuo)
                {
                    Msg("请先获取多多商品信息", true);
                    return PayResult.No;
                }
            }

            if (this.pinNeiGouRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.PinNeiGou)
                {
                    Msg("请先获取拼内购商品信息",true);
                    return PayResult.No;
                }
            }

            if (this.PuTongRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.PuTong && pddGood.type != (int)PddGoodSource.PuTongHtml)
                {
                    Msg("请先获取普通商品信息", true);
                    return PayResult.No;
                }
            }

            if (this.ZhiBoRadioButton.Checked)
            {
                if (pddGood.type != (int)PddGoodSource.ZhiBo)
                {
                    Msg("请先获取直播商品信息", true);
                    return PayResult.No;
                }
            }

        
            var tutpl = await PddService.GetProxyIp(pddToken.pdd_user_id,yuiipRadioButton.Checked,this.GetIpUrl.Text);
            string daili = tutpl.Item1;
            string msg = tutpl.Item2;
             
            if (string.IsNullOrEmpty(daili))
            {
                Msg(msg, true);
                return PayResult.No;
            }
            Msg("使用IP：" + daili );

            if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
            {

                pddToken = await pddTokenService.CheckePddTokenStatus(pddToken);
                
                //var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken, daili);

                //if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
                //{
                //    pddToken.status = "正常";
                //}
                //else if (pddUserInfo.Content.Contains("error_code"))
                //{
                //    pddToken.status = "过期";
                //}
                //else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
                //{
                //    pddToken.status = "未知";
                //}
            }
            else
            {
                pddToken.status = "未知";
            }


            if (pddToken.status == "过期" || pddToken.status == "未知")
            {
                Msg("获取用户信息异常，小号可能过期了", true);
                return PayResult.Ignore;
            }
            

            if (this.LikeCheckBox.Checked)
            {
                await PddApi.FavoriteGood(pddToken, GetGoodId(),daili);
            }

            if (this.FavoriteMallCheckBox.Checked && !string.IsNullOrWhiteSpace(pddGood.mall_id))
            {
                string url = "http://yangkeduo.com/proxy/api/favorite/mall/like/"+ pddGood.mall_id;
                string ant = FackUtil.GetAnti(null, url);
                var res = await PddApi.FavoriteMall(pddToken, ant, pddGood.mall_id);
            }

            if (this.NickNameCheckBox.Checked)
            {
                string imageBase64 = null;
                imageBase64 = ImageUtil.GetRandomBase64Avatar(AppDomain.CurrentDomain.BaseDirectory + "avatar");

                if (string.IsNullOrWhiteSpace(imageBase64))
                {
                    Msg("获取本地头像失败，不进行更新头像", true);
                }
                else
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + "昵称.txt";
                    string nickName="";
                    if (File.Exists(path))
                    {
                        Msg("使用自定义昵称库");
                        var liens = File.ReadAllLines(path);
                        if (liens.Length > 0) 
                        {
                            Random random = new Random(Guid.NewGuid().GetHashCode());
                            nickName = liens[random.Next(0, liens.Length)];
                        }
                      
                     
                    }

                    if (string.IsNullOrWhiteSpace(nickName))
                    {
                        Msg("昵称获取失败，使用内置库");
                        nickName = RandomName.GetNickName();
                    }

                    Msg("修改昵称：" + nickName);
                    bool result = await PddApi.UpdateNickName(pddToken, nickName, daili);
                    if (!result)
                    {
                        Msg("修改昵称失败", true);
                    }

                    var signature = await PddApi.Signature(pddToken, daili);
                    if (string.IsNullOrWhiteSpace(signature))
                    {
                        Msg("头像上传失败,原因：获取上传签名异常", true);
                    }

                    string imageUrl = await PddApi.UploadAvatar(pddToken, signature, imageBase64, daili);

                    result = await PddApi.UpdateAvatar(pddToken, imageUrl, daili);
                    if (!result)
                    {
                        Msg("头像上传失败", true);
                    }
                }
            }


            try
            {
                var addresses = await PddApi.GetAllAddress(pddToken);
                if (addresses != null || addresses.Count() > 0)
                {
                    foreach (var address in addresses)
                    {
                        bool result = await PddApi.DelAddressById(pddToken, address.address_id);
                    }
                }
            }
            catch (Exception)
            {
                
            }
         


            PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
            PddAddress pddAddress =  GetRandomAddress(this.RandomAddressCheckBox.Checked, ref pddAddressDBModel);
            string addressId= await AddAddress(pddAddress, pddToken, daili);
            if (this.AutoDelAddress.Checked) 
            {
                Msg("自动删除本地地址：" + pddAddress.address);
                bool de = DataBaseHelper.SqLiteDBCon.Delete(pddAddressDBModel);
                pddAddressDBModelList.ToList().RemoveAll(x => { return x.address == pddAddressDBModel.address; });
            }


            if (string.IsNullOrWhiteSpace(addressId))
            {
                Msg("地址设置异常,准备重试一下", true);
                await Task.Delay(1000);
                
                tutpl =  await PddService.GetProxyIp(pddToken.pdd_user_id,yuiipRadioButton.Checked,  this.GetIpUrl.Text);
                daili = tutpl.Item1;
                msg = tutpl.Item2;
                if (string.IsNullOrEmpty(daili))
                {
                    Msg(msg, true);
                    return PayResult.No;
                }
             //   pddAddress = GetRandomAddress(this.RandomAddressCheckBox.Checked, ref pddAddressDBModel);
                addressId = await AddAddress(pddAddress, pddToken, daili);
                if (string.IsNullOrWhiteSpace(addressId))
                {
                    Msg("地址真的设置不上，等会重新试试呀！！！", true);
                    return PayResult.Ignore;
                }
            }
            //本地订单
            Order order = new Order();
            order.address = pddAddressDBModel.address;
            order.mobile = pddAddress.mobile;
            order.name = pddAddress.name;

            if (this.PiFaRadioButton.Checked)
            {
                Msg("批发入口下单");

                CreateOrderItemListItem createOrderItemListItem = new CreateOrderItemListItem();
                createOrderItemListItem.goodsId = goodsId;
                createOrderItemListItem.skuId = skuIdStr;
                createOrderItemListItem.skuNum = this.SkuNumberIntegerTextBox.IntValue;
                return await PiFa(pddGood, pddToken, createOrderItemListItem, addressId, daili, singBuy,order);
            }

            PDDOrder pddOrder = new PDDOrder();
            pddOrder.address_id = addressId;
            var goods = new List<Goods>();
            Goods good = new Goods();
            good.sku_id = skuIdStr.ToString();
            good.goods_id = goodsId.ToString();
            good.sku_number = this.SkuNumberIntegerTextBox.IntValue;
            goods.Add(good);
            pddOrder.goods = goods;


            if (this.GroupTypeCombobox.Text == "单买")
            {
                pddOrder.group_id = gIdList.FirstOrDefault();
            }
            else if (this.GroupTypeCombobox.Text == "参团")
            {
                var groupRes = await PddApi.Leibniz(pddToken, pddOrder.goods[0].goods_id, daili);
                if (gIdList.Count == 2)
                {
                    pddOrder.group_id = gIdList[1];
                }
                if (groupRes.StatusCode == HttpStatusCode.OK)
                {

                    if (!string.IsNullOrWhiteSpace(groupRes.Content))
                    {
                        var jo = JObject.Parse(groupRes.Content);
                        var local_group = jo["local_group"].ToList().FirstOrDefault()?.ToString();
                        if (!string.IsNullOrWhiteSpace(local_group))
                        {
                            var local_groupJo = JObject.Parse(local_group);
                            string group_order_id = local_groupJo["group_order_id"].ToString();
                            pddOrder.group_order_id = group_order_id;
                        }

                    }
                }
            }
            else if (this.GroupTypeCombobox.Text == "开团") 
            {
                if (gIdList.Count == 2)
                {
                    pddOrder.group_id = gIdList[1];
                }
            }
            else
            {
                if (gIdList.Count == 2)
                {
                    pddOrder.group_id = gIdList[1];
                }
                if (this.GroupTypeCombobox.Text.Contains("随机选择"))
                {
                    Random r = new Random();
                    int i = r.Next(1, 3);
                    if (i == 1)
                    {
                        var groupRes = await PddApi.Leibniz(pddToken, pddOrder.goods[0].goods_id, daili);
                        if (groupRes.StatusCode == HttpStatusCode.OK)
                        {

                            if (string.IsNullOrEmpty(groupRes.Content))
                            {
                                var jo = JObject.Parse(groupRes.Content);
                                var local_group = jo["local_group"].ToList().FirstOrDefault()?.ToString();
                                if (!string.IsNullOrWhiteSpace(local_group))
                                {
                                    var local_groupJo = JObject.Parse(local_group);
                                    string group_order_id = local_groupJo["group_order_id"].ToString();
                                    pddOrder.group_order_id = group_order_id;
                                }

                            }
                        }

                    }
                }

             
            }

            pddOrder.activity_id = pddGood.atvid;

            if (this.PuTongRadioButton.Checked)
            {
                Msg("普通入口下单");

                return await PuTongOrder(pddToken, pddOrder, daili, singBuy, coupon, order);
            }

            if (this.DuoDuoRadioButton.Checked)
            {
                Msg("多多入口下单");
                return await DuoDuoOrder(pddGood, pddToken, pddOrder, daili, singBuy, order, coupon);
            }

            if (this.pinNeiGouRadioButton.Checked)
            {
                Msg("拼内购下单");

                return await PinNeiGouOrder(pddToken, pddOrder, daili, singBuy, pddGood, order);
            }

            if (this.ZhiBoRadioButton.Checked)
            {
                Msg("直播下单");

                return await ZhiBoOrder(pddToken, pddOrder, daili, singBuy, pddGood, order);
            }
            return PayResult.Ignore;
        }

        private async Task<PayResult> PinNeiGouOrder(PddToken pddToken, PDDOrder pddOrder, string daili, bool singBuy, PddGood pddGood, Order order)
        {
            string errorMsg = "";
            var OrderResponse =await PddService.PinNeiGouOrder(pddToken, pddOrder, pddGood, daili,errorMsg);

          
            //var OrderResponse = await PddApi.PddOrder(pddToken.pdd_user_id, pddToken.PDDAccessToken, pddOrder, this.SourceTextBox.Text, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            Msg("下单成功，订单号：" + pDDOrderResponse.order_sn);

            pddToken.last_order_sn = pDDOrderResponse.order_sn;

            pddTokenService.UpdateToken(pddToken, true);
    
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.skuName = this.SkuComboBox.Text;
            order.pay_url = "";
            order.order_type = "拼内购";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();

            if (this.OnlyPrePayCheckBox.Checked)
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            Msg("生成支付链接成功");


            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            order.pay_url = url;
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔" + IntervalTime + "秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }


            return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;
        }

        private async Task<PayResult> ZhiBoOrder(PddToken pddToken, PDDOrder pddOrder, string daili, bool singBuy, PddGood pddGood, Order order)
        {
            string errorMsg = "";
            var OrderResponse = await PddService.ZhiBoOrder(pddToken, pddOrder, pddGood, daili, errorMsg);


            //var OrderResponse = await PddApi.PddOrder(pddToken.pdd_user_id, pddToken.PDDAccessToken, pddOrder, this.SourceTextBox.Text, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            Msg("下单成功，订单号：" + pDDOrderResponse.order_sn);

            pddToken.last_order_sn = pDDOrderResponse.order_sn;

            pddTokenService.UpdateToken(pddToken, true);
         
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.skuName = this.SkuComboBox.Text;
            order.pay_url = "";
            order.order_type = "直播订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();

            if (this.OnlyPrePayCheckBox.Checked)
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            Msg("生成支付链接成功");


            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            order.pay_url = url;
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔" + IntervalTime + "秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }


            return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;
        }


        private string GetGoodId() 
        {
            string tempStr = this.GoodComboBox.Text.Replace("\n", "");
            return tempStr.Replace("\r", "").Trim();
        }
     
        private void Msg(string msg, bool error = false, bool enter = true)
        {
            if (string.IsNullOrWhiteSpace(msg)) { return; }
            if (error) this.LogRichTextBox.SelectionColor = Color.Red;

            LogRichTextBox.AppendText(msg);

            if (enter) LogRichTextBox.AppendText("\r\n");

            if (error) this.LogRichTextBox.SelectionColor = Color.Black;


            LogRichTextBox.ScrollToCaret();
        }


        private async Task<string> AddAddress(PddAddress pddAddress, PddToken pddToken, string daili) 
        {

            if (pddAddress == null) 
            {
                return null;
            }

            string address_id = "";
            var res = await PddApi.AddAddress(pddToken, pddAddress, daili);
            Msg("地址设置：" + pddAddress.address);

            PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
            pddAddressDBModel.address = pddAddress.address;
            pddAddressDBModel.mobile = pddAddress.mobile;
            pddAddressDBModel.name = pddAddress.name;

            if (res.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(res.Content))
            {
                dynamic dyn = JsonConvert.DeserializeObject(res.Content);
                address_id = dyn.address_id;

                return address_id;
            }
            else
            {
                LogHelper.Logger.Debug("地址设置异常：" + pddAddressDBModel.address);
                LogHelper.Logger.Debug("地址设置异常：" + res.Content);
            }

            return address_id;
        }

        private PddAddress GetRandomAddress(bool random, ref  PddAddressDBModel pddAddressDBModel)
        {
            PddAddress pddAddress = new PddAddress();
            //PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
            int index;
            while (true)
            {

                Random r = new Random(Guid.NewGuid().GetHashCode());
                if (pddAddressDBModelList.Count() == 0)
                {
                    ShowErrorDialog("地址库数据为空");
                    return null;
                }
                index = r.Next(0, pddAddressDBModelList.Count());
                pddAddressDBModel = pddAddressDBModelList.ToList()[index];

                if (pddAddressDBModel != null)
                {

                    string[] addressArr = pddAddressDBModel.address.Split(' ');
                    if (addressArr.Length != 4)
                    {
                        continue;
                    }

                    //if (!string.IsNullOrWhiteSpace(Global.Global.Province)) {
                    //    if (!addressArr[0].Contains(Global.Global.Province))
                    //    {
                    //        continue;
                    //    }
                    //}
             

                    var sheng = areaModelList.Where(x =>
                    {
                        return x.region_type == 1 && (x.region_name.Contains(addressArr[0]) || addressArr[0].Contains(x.region_name));
                    }).FirstOrDefault();
                    if (sheng == null)
                    {
                        continue;
                    }

                    var shi = areaModelList.Where(x =>
                    {
                        return x.region_type == 2 && sheng.region_id == x.parent_id && (x.region_name.Contains(addressArr[1]) || addressArr[1].Contains(x.region_name));
                    }).FirstOrDefault();

                    if (shi == null)
                    {
                        continue;
                    }

                    var xian = areaModelList.Where(x =>
                    {
                        return x.region_type == 3 && shi.region_id == x.parent_id && (x.region_name.Contains(addressArr[2]) || addressArr[2].Contains(x.region_name));
                    }).FirstOrDefault();

                    if (xian == null)
                    {
                        continue;
                    }
                    pddAddress.city_id = shi.region_id;
                    pddAddress.district_id = xian.region_id;
                    pddAddress.province_id = sheng.region_id;

                    if (nameCheckBox.Checked)
                    {
                        if (nameBeforeRadioButton.Checked)
                        {
                            pddAddress.name = this.NamePrefixTextBox.Text + pddAddressDBModel.name;
                        }
                        else
                        {
                            pddAddress.name = pddAddressDBModel.name + this.NamePrefixTextBox.Text;
                        }
                    }
                    else 
                    {
                        pddAddress.name = pddAddressDBModel.name;
                    }

                    if (addressCheckBox.Checked)
                    {
                        if (addressCeforeRadioButton.Checked)
                        {
                            pddAddress.address = this.AddressPrefixTextBox.Text + addressArr[3];
                        }
                        else
                        {
                            pddAddress.address = addressArr[3] + this.AddressPrefixTextBox.Text;
                        }
                    }
                    else 
                    {
                        pddAddress.address = addressArr[3];
                    }

                    pddAddress.mobile = pddAddressDBModel.mobile;
                 
                    pddAddress.is_default = "0";
                    break;
                }

            }
            return pddAddress;
            //var res = await PddApi.AddAddress(pddToken, pddAddress, daili);
            //Msg("地址设置：" + pddAddressDBModel.address);
            //if (res.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(res.Content))
            //{
            //    dynamic dyn = JsonConvert.DeserializeObject(res.Content);
            //    address_id = dyn.address_id;

            //    if (isDelAddress)
            //    {
            //        Msg("自动删除本地地址：" + pddAddressDBModel.address);
            //        DataBaseHelper.SqLiteDBCon.Delete(pddAddressDBModel);
            //        pddAddressDBModelList.ToList().RemoveAt(index);
            //    }
            //    return address_id;
            //}
            //else 
            //{
            //    LogHelper.Logger.Debug("地址设置异常："+ pddAddressDBModel.address);
            //    LogHelper.Logger.Debug("地址设置异常："+ res.Content);
            //}

            //return address_id;

        }


        private async Task<PayResult> PiFa(PddGood pdd1, PddToken pddToken, CreateOrderItemListItem createOrderItemListItem, string addressId, string daili, bool singBuy, Order order)
        {
            string urlAnti = "https://mms.pinduoduo.com/pifa/goods/singleBuy";
            string ant = FackUtil.GetAnti(null, urlAnti);

            if (string.IsNullOrWhiteSpace(ant))
            {
                Msg("下单签名失败，请在中间切换个网试试看行不", true);
                return PayResult.Ignore;
            }

            var res = await PddPiFaApi.SingleBuy(pddToken, createOrderItemListItem, ant, daili);
            if (res.StatusCode != HttpStatusCode.OK)
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }

            var jo = JObject.Parse(res.Content);

            var success = jo["success"].ToString();
            var errorCode = jo["errorCode"].ToString();
            var errorMsg = jo["errorMsg"].ToString();
            if (success.ToLower() != "true")
            {
                if (errorCode == "6000005")
                {
                    Msg(errorMsg, true);
                    return PayResult.Ignore;
                }
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }

            var qrKey = jo["result"]["qrKey"].ToString();

            if (string.IsNullOrWhiteSpace(qrKey))
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }
            var curl = jo["result"]["curl"].ToString();

            string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, curl, daili);
            var pifaClientOrderCreate = PaserOrderHtml(html);
            if (pifaClientOrderCreate == null)
            {
                return PayResult.Ignore;
            }
            urlAnti = "https://mobile.yangkeduo.com/proxy/api/api/pifa-client/order/order_create";
            ant = FackUtil.GetAnti(null, urlAnti);

            pifaClientOrderCreate.secret_key = qrKey;
            pifaClientOrderCreate.anti_content = ant;
            pifaClientOrderCreate.page_id = "";
            pifaClientOrderCreate.address_id = double.Parse(addressId);
            res = await PddPiFaApi.PiFaOrderCreate(pddToken, pifaClientOrderCreate, daili);
            if (res.StatusCode != HttpStatusCode.OK)
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
            }

            jo = JObject.Parse(res.Content);

            success = jo["success"].ToString();

            if (success.ToLower() != "true")
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }

            var order_sns = jo["result"]["order_sns"].FirstOrDefault()?.ToString();
            var parent_order_sn = jo["result"]["parent_order_sn"].ToString();

            pddToken.last_order_sn = order_sns;
       
            pddTokenService.UpdateToken(pddToken, true);

            Msg("下单成功，订单号：" + parent_order_sn);
     
            order.goodsId = createOrderItemListItem.goodsId.ToString();
            order.orderSn = order_sns;
            order.parent_order_sn = parent_order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = createOrderItemListItem.skuNum.ToString();
            order.order_type = "批发订单";

            if (this.OnlyPrePayCheckBox.Checked) 
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

          
            res = await PddPiFaApi.PiFPrepay(pddToken, parent_order_sn, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                Msg("批发下单失败", true);
                return PayResult.Ignore;
            }

            Msg("生成支付链接成功");

            jo = JObject.Parse(res.Content);
            var query = jo["query"];
            var total_fee = jo["query"]["total_fee"].ToString();

            var gateway_url = jo["gateway_url"];

            StringBuilder stringBuilder = new StringBuilder();
            foreach (JToken grandChild in query)
            {
                var p = grandChild as JProperty;
                string s = p.Name + ":" + p.Value;
                stringBuilder.Append(p.Name);
                stringBuilder.Append("=");
                stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
                stringBuilder.Append("&");
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            string url = gateway_url + "?" + stringBuilder.ToString();
            order.pay_url = url;
            order.goodsMoney = double.Parse(total_fee) * 100 + "";
         
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔" + IntervalTime + "秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }

            return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;

        }

        private async Task<PayResult> PuTongOrder(PddToken pddToken, PDDOrder pddOrder, string daili, bool singBuy,string coupon, Order order)
        {
            string promotion_id = "";

         

            if (!string.IsNullOrWhiteSpace(coupon)) 
            {
                //http://mobile.yangkeduo.com/proxy/api/api/promotion/auto_take_merchant_coupon?pdduid=6878012836386&is_back=1
                string urlAnti = "http://mobile.yangkeduo.com/proxy/api/api/promotion/auto_take_merchant_coupon";
                string ant = FackUtil.GetAnti(null, urlAnti);

                if (string.IsNullOrWhiteSpace(ant))
                {
                    Msg("领取优惠券签名失败，不使用优惠券了", true);
                }
                else 
                {
                    var ress = await PddApi.AutoTakeMerchantCoupon(pddToken, ant, coupon, daili);
                    if (ress.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(ress.Content)) 
                    {
                        Msg("领取优惠券成功");
                        var batchObj =  JObject.Parse(ress.Content);
                        promotion_id = batchObj["promotion_identity_vo"]["promotion_id"].ToString();
                    }
                }

            
            }

            pddOrder.merchant_coupon_id = promotion_id;
            var OrderResponse = await PddApi.PddOrder(pddToken.pdd_user_id, pddToken.PDDAccessToken, pddOrder, this.SourceTextBox.Text, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;
            }

            Msg("下单成功，订单号：" + pDDOrderResponse.order_sn);
         
            pddToken.last_order_sn = pDDOrderResponse.order_sn;
         
            pddTokenService.UpdateToken(pddToken, true);
   
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.skuName = this.SkuComboBox.Text;
            order.pay_url = "";
            order.order_type = "普通订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();

            if (this.OnlyPrePayCheckBox.Checked)
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                Msg("下单失败,订单预付失败", true);
                return PayResult.Ignore;
            }

            Msg("生成支付链接成功");


            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            order.pay_url = url;
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔" + IntervalTime + "秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }


            return AutoPay(url, this.PayPassword.Text,!singBuy) ? PayResult.OK : PayResult.Ignore;
        }

        private async Task<PayResult> DuoDuoOrder(PddGood pddGood, PddToken pddToken, PDDOrder pddOrder, string daili, bool singBuy, Order order, string coupon)
        {


            // string url = "https://mobile.yangkeduo.com/order_checkout.html?sku_id=618358869209&group_id=37638976781&goods_id=147655719175&goods_number=1&page_from=29&_oc_pid=20929712_208780123&_oc_duoduo_type=2&_oc_cps_sign=CC_210803_20929712_208780123_95a061a50b4f44eb567f7d068c05f221&_oc_mkt_tr_sc=ddjb_goods_coupon&_oc_mkt_tr_token=h73p3g2dlmnzgmhw3rjo6kp4fy33ovxbn5ugccwoq4ueggzhnmdzhmqnzkvo4dnxa4lvkcx4juitm&_oc_mkt_domain=222&refer_page_element=open_btn&source_channel=0&refer_page_name=goods_detail&refer_page_id=10014_1627991184342_0edoxq4lpp&refer_page_sn=10014&_x_ddjb_id=20929712_208780123|CC_210803_20929712_208780123_95a061a50b4f44eb567f7d068c05f221";

            //DuoDuoOrder duoDuoOrder = new DuoDuoOrder();
            //duoDuoOrder.group_id = pddOrder.group_id;

            //duoDuoOrder.goods = new List<GoodsItem>();
            //duoDuoOrder.goods.Add(new GoodsItem(pddOrder.goods.FirstOrDefault()));
            //duoDuoOrder.address_id = double.Parse(pddOrder.address_id);

            //DuoDuoAttribute_fields duoDuoAttribute_Fields = new DuoDuoAttribute_fields();
            //duoDuoAttribute_Fields.cps_sign = pddGood.cps_sign;
            //duoDuoAttribute_Fields.DUO_DUO_PID = pddGood.duo_duo_pid;
            //duoDuoOrder.attribute_fields = duoDuoAttribute_Fields;

            string promotion_id = "";

            if (!string.IsNullOrWhiteSpace(coupon))
            {
                
                string urlAnti1 = "http://mobile.yangkeduo.com/proxy/api/api/promotion/auto_take_merchant_coupon";
                string ant1 = FackUtil.GetAnti(null, urlAnti1);

                if (string.IsNullOrWhiteSpace(ant1))
                {
                    Msg("领取优惠券签名失败，不使用优惠券了", true);
                }
                else
                {
                    var ress = await PddApi.AutoTakeMerchantCoupon(pddToken, ant1, coupon, daili);
                    if (ress.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(ress.Content))
                    {
                        Msg("领取优惠券成功");
                        var batchObj = JObject.Parse(ress.Content);
                        promotion_id = batchObj["promotion_identity_vo"]["promotion_id"].ToString();
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(pddGood.merchantBatchSn))
            {

                string urlAnti1 = "https://api.pinduoduo.com/api/daenerys/take_coupon_v2";
                string ant1 = FackUtil.GetAnti(null, urlAnti1);

                if (string.IsNullOrWhiteSpace(ant1))
                {
                    Msg("领取优惠券签名失败，不使用优惠券了", true);
                }
                else
                {
                    TakeCoupon takeCoupon = new TakeCoupon();
                    takeCoupon.anti_content = ant1;
                    takeCoupon.couponSn = pddGood.merchantBatchSn;
                    long mailLong;
                    long.TryParse( pddGood.mall_id, out mailLong);
                    takeCoupon.mallId = mailLong;
                    takeCoupon.goodsId = pddGood.good_id;
                    takeCoupon.pid = pddGood.duo_duo_pid;

                    var ress = await PddApi.take_coupon_v2(pddToken, takeCoupon, daili);
                    if (ress.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(ress.Content))
                    {
                        Msg("领取优惠券成功");
                       // var batchObj = JObject.Parse(ress.Content);
                      //  promotion_id = batchObj["promotion_identity_vo"]["promotion_id"].ToString();
                    }
                }
            }


            DuoDuoOrder duoDuoOrder = new DuoDuoOrder();
            duoDuoOrder.group_id = pddOrder.group_id;
            duoDuoOrder.activity_id = pddOrder.activity_id;
            duoDuoOrder.goods = new List<GoodsItem>();
            duoDuoOrder.goods.Add(new GoodsItem(pddOrder.goods.FirstOrDefault()));
            duoDuoOrder.address_id = double.Parse(pddOrder.address_id);

            DuoDuoAttribute_fields duoDuoAttribute_Fields = new DuoDuoAttribute_fields();
            duoDuoAttribute_Fields.cps_sign = pddGood.cps_sign;
            duoDuoAttribute_Fields.DUO_DUO_PID = pddGood.duo_duo_pid;
            duoDuoOrder.attribute_fields = duoDuoAttribute_Fields;
            //duoDuoOrder.merchant_coupon_id = pddGood.merchantBatchSn;
           // var OrderResponse = await PddApi.PddOrderDuoDuo(pddToken, duoDuoOrder, daili);

            //if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            //{
            //    LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
            //    MessageBox.Show("下单失败,请重新获取商品数据试试！");
            //}

            string errorMsg ="";
            //DuoDuoOrderNew duoDuoOrder  =  await PddService.DuoDuoOrder(pddToken,pddOrder,pddGood,daili,errorMsg);
            if (duoDuoOrder == null) 
            {
                Msg("下单失败！", true);
                return PayResult.No;
            }
            string urlAnti = "https://mobile.yangkeduo.com/proxy/api/order";
            string ant = FackUtil.GetAnti(null, urlAnti);

            if (string.IsNullOrWhiteSpace(ant))
            {
                errorMsg = "下单签名失败";
                Msg("下单签名失败！", true);
                return PayResult.No;
            }

            duoDuoOrder.anti_content = ant;

            var OrderResponse = await PddApi.PddOrderDuoDuo(pddToken, duoDuoOrder, daili);

            if (OrderResponse.StatusCode == HttpStatusCode.Forbidden)
            {
                LogHelper.Logger.Error("下单失败:" + OrderResponse.Content);
                Msg("下单失败,请重新获取商品数据试试！", true);
                var jo =JObject.Parse(OrderResponse.Content);
                //Msg();
                return PayResult.No;

            }

            if (string.IsNullOrWhiteSpace(OrderResponse.Content))
            {
                LogHelper.Logger.Error("下单失败");
                Msg("下单失败,请重新获取商品数据试试！", true);
                return PayResult.No;

            }
            PDDOrderResponse pDDOrderResponse = null;
            try
            {
                pDDOrderResponse = JsonConvert.DeserializeObject<PDDOrderResponse>(OrderResponse.Content);
            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,返回数据解析失败" + OrderResponse.Content, e1);
                Msg("下单失败,返回数据解析失败！", true);
                return PayResult.Ignore;
            }

            Msg("下单成功，订单号：" + pDDOrderResponse.order_sn);
            pddToken.last_order_sn = pDDOrderResponse.order_sn;
          
            pddTokenService.UpdateToken(pddToken, true);
       
            order.goodsId = pddOrder.goods.FirstOrDefault().goods_id;
            order.orderSn = pDDOrderResponse.order_sn;
            order.uid = pddToken.pdd_user_id;
            order.buyTime = DateTime.Now.ToString();
            order.skuNumber = pddOrder.goods.FirstOrDefault().sku_number.ToString();
            order.pay_url = "";
            order.order_type = "多多订单";
            order.goodsMoney = pDDOrderResponse.order_amount.ToString();

            if (this.OnlyPrePayCheckBox.Checked)
            {
                order.orderState = "未支付";
                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
                Msg("先下单后支付模式，任务完成");
                return PayResult.OK;
            }

            PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
            pDDOrderPrepay.pay_app_id = 9;
            pDDOrderPrepay.version = 3;
            pDDOrderPrepay.order_sn = pDDOrderResponse.order_sn;
            pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + pDDOrderResponse.order_sn + "&prepay_type=";
            pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

            var res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

            if (res.StatusCode != HttpStatusCode.OK)
            {
                Msg("下单失败,订单预付失败！", true);
                return PayResult.Ignore;
            }

            //订单预付
            PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
            try
            {
                pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

            }
            catch (Exception e1)
            {
                LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                Msg("下单失败,订单预付失败！", true);
                return PayResult.Ignore;
            }
            Msg("生成支付链接成功");

            string query = GetUriParam(pDDOrderPrepayResponse.query);
            string url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            order.pay_url = url;
            await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
            await PddApi.DelAddressById(pddToken, pddOrder.address_id, daili);

            int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
            int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;
          
            if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime) 
            {
                Random r = new Random();
                int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
                Msg("付款间隔"+IntervalTime+"秒");
                await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
            }

            return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;
        }

        private PifaClientOrderCreate PaserOrderHtml(string html)
        {
            Regex reg = new Regex("window.rawData=(?<key2>.*?)};");
            Match match = reg.Match(html);
            string tempStr = match.Groups["key2"].Value;
            if (string.IsNullOrWhiteSpace(tempStr))
            {
                Msg("解析数据失败", true);
                return null;
            }
            PifaClientOrderCreate pifaClientOrderCreate = new PifaClientOrderCreate();
            pifaClientOrderCreate.sku_vos = new List<Sku_vosItem>();
            Sku_vosItem sku_VosItem = new Sku_vosItem();
            var jo = JObject.Parse(tempStr + " }");
            var goodsListStore = jo["store"]["goodsListStore"]["goodsList"].ToArray();
            var frontEnv = jo["store"]["envStore"]["frontEnv"].ToObject<int>();
            //var addressId = jo["store"]["addressInfoStore"]["addressId"].ToObject<double>();

            var goods = goodsListStore.FirstOrDefault();
            string goods_id = goods["goodsId"].ToString();
            string group_id = goods["groupId"].ToString();
            string sku_id = goods["skuId"].ToString();
            string sku_number = goods["skuNumber"].ToString();

            sku_VosItem.goods_id = double.Parse(goods_id);
            sku_VosItem.group_id = double.Parse(group_id);
            sku_VosItem.sku_id = double.Parse(sku_id);
            sku_VosItem.sku_number = int.Parse(sku_number);
            pifaClientOrderCreate.front_env = frontEnv;
            pifaClientOrderCreate.sku_vos.Add(sku_VosItem);

            return pifaClientOrderCreate;
        }


        /// <summary>
        /// Model对象转换为uri网址参数形式
        /// </summary>
        /// <param name="obj">Model对象</param>
        /// <param name="url">前部分网址</param>
        /// <returns></returns>
        public static string GetUriParam(object obj, string url = "")
        {
            PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            StringBuilder sb = new StringBuilder();
            sb.Append(url);
            //sb.Append("?");
            foreach (var p in propertis)
            {
                var v = p.GetValue(obj, null);
                if (v == null) v = "";

                sb.Append(p.Name);
                sb.Append("=");
                sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式，HttpUtility.UrlEncode是小写
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }

        //private async void UserDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (e.RowIndex < 0)
        //    {
        //        return;
        //    }
        //    PddToken pddToken = this.UserDataGridView.Rows[e.RowIndex].DataBoundItem as PddToken;

        //    if (pddToken == null)
        //    {
        //        return;
        //    }

        //    DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)(this.UserDataGridView.Rows[this.UserDataGridView.CurrentCell.RowIndex].Cells[0]);
        //    if (Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue) == false)
        //    {
        //        dataGridViewCheckBoxCell.Value = true;
        //    }
        //    else
        //    {
        //        dataGridViewCheckBoxCell.Value = false;
        //    }


        //    if (!string.IsNullOrWhiteSpace(pddToken.PDDAccessToken))
        //    {
        //        var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

        //        if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.OK)
        //        {
        //            pddToken.status = "正常";
        //        }
        //        else if (pddUserInfo.Content.Contains("error_code"))
        //        {
        //            pddToken.status = "过期";
        //        }
        //        else if (pddUserInfo.StatusCode == System.Net.HttpStatusCode.NotFound)
        //        {
        //            pddToken.status = "未知";
        //        }
        //        pddTokenService.UpdateToken(pddToken, true);
               
        //    }
        //    else
        //    {
        //        pddToken.status = "未知";
        //    }
        //    this.UserDataGridView.Refresh();
        //}

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            if (StartTask)
            {
                Msg("请等待任务完成", true);
                return;
            }
            StartTask = true;
            StopTask = false;
            int startIndex = this.UserStartIndex.IntValue;
            int taskNum = this.TaskNum.IntValue;
            var tokens = pddTokenService.GetShuaDanToken();
            if (taskNum > tokens.Count() || startIndex > tokens.Count() || startIndex + taskNum - 1 > tokens.Count())
            {
                ShowErrorDialog("小号太少了，不能完成任务");
                StartTask = false;
                return;
            }

            if (pddAddressDBModelList.Count() == 0) {
                Msg("地址为空，请添加地址再下单", true);
            }

            for (int i = 0; i < taskNum; i++)
            {
                var token = tokens.ElementAt(startIndex - 1);
                Msg("开始第" + (i + 1) + "个任务 使用小号：" + token.pdd_user_id);
                try
                {
                    var result = await SingBuyGood(token);
                    if (result == PayResult.No)
                    {
                        Msg("遇到错误任务终止", true);
                        break;
                    }
                }
                catch (Exception e1)
                {
                    LogHelper.Logger.Error("下单错误：",e1);
                    Msg("遇到错误任务终止", true);
                }
           
                startIndex++;
                Msg("第" + (i + 1) + "个任务完成");
                this.UserStartIndex.IntValue = this.UserStartIndex.IntValue + 1;
                int PayOrderStartIntervalTime = this.PayOrderStartIntervalTimeTextBox.IntValue;
                int PayOrderEndIntervalTime = this.PayOrderEndIntervalTimeTextBox.IntValue;

                if (PayOrderStartIntervalTime > 0 && PayOrderEndIntervalTime > 0 && PayOrderEndIntervalTime > PayOrderStartIntervalTime)
                {
                    Random r = new Random();
                    int IntervalTime = r.Next(PayOrderStartIntervalTime, PayOrderEndIntervalTime);
                    Msg("下单间隔" + IntervalTime + "秒");
                    await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
                }
                if (StopTask) 
                {
                    break;
                }
            }
            StartTask = false;
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {

        }

        //private async void uiButton7_Click(object sender, EventArgs e)
        //{
        //    string goodId = GetGoodId();


        //    foreach (PddToken pddToken in pddTokenService.GetShuaDanToken())
        //    {
              
        //        var pddUserInfo = await PddApi.GetPddMyInfo(pddToken.pdd_user_id, pddToken.PDDAccessToken);

        //        if (string.IsNullOrWhiteSpace(pddUserInfo.Content))
        //        {
        //            //MessageBox.Show("获取用户信息异常，小号可能过期了");
        //            continue;
        //        }
        //        await PddApi.FavoriteGood(pddToken, goodId);

        //        //if (string.IsNullOrWhiteSpace(text))
        //        //{
        //        //    //MessageBox.Show("小号收藏失败");
        //        //}
        //    }

        //    ShowSuccessDialog("全部收藏完成");
        //}

        //private void uiButton3_Click(object sender, EventArgs e)
        //{
        //    //调用系统默认的浏览器
        //    System.Diagnostics.Process.Start("http://www.pdd88.top");
        //}

        //private void uiButton2_Click(object sender, EventArgs e)
        //{
        //    OpenFileDialog dialog = new OpenFileDialog();
        //    dialog.Multiselect = true;//该值确定是否可以选择多个文件
        //    dialog.Title = "请选择文件夹";
        //    dialog.Filter = "所有文件(*.txt)|*.txt";
        //    if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        //    {
        //        string file = dialog.FileName;
        //        string text = File.ReadAllText(file);
        //        if (string.IsNullOrWhiteSpace(text))
        //        {
        //            MessageBox.Show("数据为空");
        //            return;
        //        }
        //        string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        //        var PddTokenList = pddTokenService.GetAllToken();
        //        foreach (var item in striparr)
        //        {
        //            try
        //            {
        //                string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
        //                if (sArray1.Length != 3)
        //                {
        //                    continue;
        //                }
        //                string qqOrPhone = sArray1[0];
        //                string uid = sArray1[1];
        //                string token = sArray1[2];
        //                PddToken pddToken = new PddToken();
        //                pddToken.pdd_user_id = uid;
        //                pddToken.PDDAccessToken = token;
        //                var pddT = PddTokenList.Where(x =>
        //                {
        //                    return x.pdd_user_id == uid;
        //                }).FirstOrDefault();
        //                if (pddT != null)
        //                {
        //                    pddToken.id = pddT.id;
        //                    pddTokenService.UpdateToken(pddToken);
        //                    //DataBaseHelper.SqLiteDBCon.Update<PddToken>(pddToken);
        //                }
        //                else
        //                {
        //                    pddTokenService.InsertToken(pddToken);
        //                    //var reslut = DataBaseHelper.SqLiteDBCon.Insert<PddToken>(pddToken);
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                LogHelper.Logger.Error("导入小号失败", ex);
        //            }

        //        }

        //        var tokens = pddTokenService.GetShuaDanToken();
        //        UserDataGridViewPagination.DataSource = tokens;
        //        UserDataGridViewPagination.ActivePage = 1;
        //    }
        //}

        //private void uiButton4_Click(object sender, EventArgs e)
        //{
        //    if (this.UserDataGridView.SelectedRows.Count < 0)
        //    {
        //        return;
        //    }

        //    PddToken pddToken = this.UserDataGridView.CurrentRow.DataBoundItem as PddToken;
        //    if (pddToken == null)
        //    {
        //        return;
        //    }

        //    if (ShowAskDialog("您确定删除吗") )
        //    {

        //        bool reslut = DataBaseHelper.SqLiteDBCon.Delete(pddToken);
        //        if (reslut)
        //        {
        //            //this.UserDataGridView.Rows.Remove(this.UserDataGridView.CurrentRow);
        //            var tokens = pddTokenService.GetAllToken();
        //            UserDataGridViewPagination.DataSource = tokens.Where(x => x.account_type != 1).ToList();
        //        }
        //    }
        //}

        private void uiLabel9_Click(object sender, EventArgs e)
        {

        }

        //private void PayPassword_TextChanged(object sender, EventArgs e)
        //{
        //    browserFrom.ZhiFuPassword = this.PayPassword.Text;
        //}

        private async void uiButton5_Click(object sender, EventArgs e)
        {
            AutoPay("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1121060417200890744164006953&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1121060417200890744164006953&total_fee=14.06&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210604-234178530080976%26prepay_type%3D&sign=Mg8qDw%2BJkaz6sU7pn2iRRXjS9i62R%2FalqtIGEr6KUrJud2W%2B7IEA0jVA9LVGxgqa6yGYiMZ%2B%2FrCRiLmtYL7nuRfDlbVTdhFT%2BnLV52tPCIJaEjPTzL%2FQvpGB5Gx45P30RmPm%2Bf3h1N6riOvrDUKXjpjjHcChnbeLQaNur80rdQc%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-06-05%2017%3A14", this.PayPassword.Text);
            //  var driver = GetDriver("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1221060415200888338109001531&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1221060415200888338109001531&total_fee=15.96&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210604-634435666660517%26prepay_type%3D&sign=XLOdkUgrIYBoYdJQL9%2BynyQL5v5J2c6%2BBRDH1iJioGDGQU5GAd3N2A0qZRsbO5o4O5hexew14fSqAXk%2BR0ERnvFlYdn%2B8iJzntq3rxj4RV75XQ0%2FLW90TTTSLHNEo4g0Elz2CPr9bB3ITiPVRvSRWMtMKUkuZvW36BaOnxNFXWw%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-06-05%2015%3A39");
            // var driver = GetDriver("https://mapi.alipay.com/gateway.do?service=alipay.wap.create........................");
            //try
            //{
            //    var zhifuButton = By.XPath("//*[@id=\"cashierPreConfirm\"]/div[2]/button");
            //    driver.FindElement(zhifuButton).Click();
            //    var payInput = By.XPath("//*[@id=\"pwd_unencrypt\"]");
            //    driver.SwitchTo().DefaultContent();
            //    driver.FindElement(payInput).SendKeys("248786");
            //    Thread.Sleep(1000);
            //    string url = driver.Url;
            //    if (url.Contains("https://mclient.alipay.com/h5/cashierPay.htm?awid="))
            //    {
            //        ShowSuccessNotifier("任务成功");
            //        driver.Close();
            //    }
            //    else {
            //        ShowSuccessNotifier("任务失败");
            //    }
            //}
            //catch (Exception)
            //{
            //}

        }

        private void PayPassword_TextChanged(object sender, EventArgs e)
        {
            //string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\pay.tmp";
            //File.WriteAllText(path, this.PayPassword.Text);

            string path = AppDomain.CurrentDomain.BaseDirectory + "tmp\\pay.tmp";
            Global.Global.PayPassword = this.PayPassword.Text;
            File.WriteAllText(path, this.PayPassword.Text);
        }

        private void PayPassword_Leave(object sender, EventArgs e)
        {
 
        }



        private bool AutoPay(string url, string password, bool isClose = false, int timeOut = 5000)
        {
            if (qudongPayCheckBox.Checked)
            {
                AutoPayFrom browserFrom = new AutoPayFrom(url, this.PayPassword.Text,true);
              //  BrowserFrom browserFrom = new BrowserFrom(true);
                browserFrom.AutoPay(url, this.PayPassword.Text, true, timeOut);
                var res = browserFrom.ShowDialog();
                if (res == DialogResult.OK)
                {
                    return true;
                }
                return false;
            }
            else 
            {
                //AutoPayFrom browserFrom = new AutoPayFrom("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify-sh5.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1121070113500464580528000984&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1121070113500464580528000984&total_fee=11.9&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210701-107143496583801%26prepay_type%3D&sign=eK49%2B7hVGGrlY1cyEeGrV4kZgxKbRpbOUTuk2f9wtL7DH6WfbK21pHp9QgvalWDUPblSoVYmVHgsIRJHlZjdyf78gm%2FPsVyceNVJIM2P%2BZpmztl3cvt32%2FGFxKo4%2Bt%2FipLp%2BAmB3bV%2FPWddVVJOrHPduEhnTwE4mMQ46fhyenVc%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-07-02%2013%3A24", "123");
                //var res = browserFrom.ShowDialog();
                AutoPayFrom browserFrom = new AutoPayFrom(url, this.PayPassword.Text);
                //browserFrom.AutoPay(url, this.PayPassword.Text, true, timeOut);
                var res = browserFrom.ShowDialog();
                if (res == DialogResult.OK)
                {
                    return true;
                }
                return false;
            }
           
        }

        private void uiButton5_Click_1(object sender, EventArgs e)
        {
            // AutoPay();
            //string processPath = AppDomain.CurrentDomain.BaseDirectory + "AutoPay.exe";
            //process = Process.Start(processPath, "1");
            //BrowserFrom browserFrom = new BrowserFrom();
            //browserFrom.action = UpdateGoodInfo;
            //browserFrom.LoadUrl("www.baidu.com", 5000);
            //browserFrom.Show();
            //var service = ChromeDriverService.CreateDefaultService();
            //IWebDriver driver = iWebChrome(service);
            //driver.Navigate().GoToUrl("https://fanyi.baidu.com/?aldtype=16047#auto/zh");
            //Thread.Sleep(3000);
            //driver.Navigate().GoToUrl("https://www.baidu.com");
            //Thread.Sleep(3000);
            //driver.Quit();
            //service.Dispose();

            AutoPay("https://mapi.alipay.com/gateway.do?service=alipay.wap.create.direct.pay.by.user&partner=2088911201740274&seller_id=pddzhifubao%40yiran.com&payment_type=1&notify_url=https%3A%2F%2Fpaynotify.pinduoduo.com%2Fnotify%2F9&out_trade_no=XP1221060419201989076476002231&subject=%E5%95%86%E6%88%B7%E5%8D%95%E5%8F%B7XP1221060419201989076476002231&total_fee=16.4&return_url=http%3A%2F%2Fmobile.yangkeduo.com%2Ftransac_wappay_callback.html%3Forder_sn%3D210604-132500706073493%26prepay_type%3D&sign=TKycjMB0ftRWTO9PaiIEZmIlKhy%2BjqTWeZwrnZ9bygvywWfo2GDGMBdd4r%2Fu8uUdUO3CZhqzpMzcAtJBOGwVa65MjDSYrl%2F84GlATGKAtr8EKpDeP%2Be6TUOvEm5Vp2PrejpwSB9LDDuFthmw667X9J%2Bno4WeFQjikoDrNgtRLMM%3D&sign_type=RSA&goods_type=1&_input_charset=utf-8&it_b_pay=2021-06-05%2019%3A46", this.PayPassword.Text);
        }


        public static IWebDriver iWebChrome(ChromeDriverService chromeDriverService)
        {
            ChromeOptions options = new ChromeOptions();
            options.DebuggerAddress = "127.0.0.1:22222";
            chromeDriverService.HideCommandPromptWindow = true;//关闭每次调试时打开的CMD
            IWebDriver driver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(10));
            return driver;
        }

     

        private void UserDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        //private void uiButton5_Click_2(object sender, EventArgs e)
        //{
        //    var pddTokenList = GetSelectRows();
        //    if (pddTokenList.Count() < 1)
        //    {
        //        ShowWarningDialog("请先勾选要删除的数据");
        //        return;
        //    }

        //    if (ShowAskDialog("您确定删除这" + pddTokenList.Count() + "个小号吗?"))
        //    {
        //        foreach (var pddToken in pddTokenList)
        //        {
        //            bool reslut = DataBaseHelper.SqLiteDBCon.Delete(pddToken);
        //        }
        //        var tokens = pddTokenService.GetShuaDanToken();
        //        UserDataGridViewPagination.DataSource = tokens;
        //    }
        //}

     
        //private void uiCheckBox1_ValueChanged(object sender, bool value)
        //{
        //    foreach (DataGridViewRow dataGridViewRow in this.UserDataGridView.Rows)
        //    {
        //        var pddToken = dataGridViewRow.DataBoundItem as PddToken;
        //        pddToken.IsCheck = uiCheckBox1.Checked;
        //    }
        //    this.UserDataGridView.Refresh();
        //}
      

        private async void uiButton8_Click(object sender, EventArgs e)
        {

        }

        private void GetIpUrl_TextChanged(object sender, EventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "dailiUrl",this.GetIpUrl.Text, IniHelper.IniPathFile);
        }

        private void yuiipRadioButton_MouseClick(object sender, MouseEventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "isSetDaili", "false", IniHelper.IniPathFile);
        }

        private void uiRadioButton1_MouseClick(object sender, MouseEventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "isSetDaili", "true", IniHelper.IniPathFile);
        }

        private void qudongPayCheckBox_MouseClick(object sender, MouseEventArgs e)
        {
            IniHelper.WriteKeyToIni("STARTUP", "PayMode", this.qudongPayCheckBox.Checked.ToString(), IniHelper.IniPathFile);
        }

        private void uiButton1_Click_1(object sender, EventArgs e)
        {
            string coupon = this.CouponListComboBox.SelectedValue?.ToString();
        }

        private void uiButton1_Click_2(object sender, EventArgs e)
        {
;           StopTask = true;
        }

        private async void uiButton3_Click_1(object sender, EventArgs e)
        {
            // string url = "http://mobile.yangkeduo.com/goods.html?goods_id=249428273484";

              var tokens = pddTokenService.GetShuaDanToken();

            // string msg="";
            // string daili = await PddService.GetProxyIp(true, msg,this.GetIpUrl.Text);
            //var res =  await  GetTransacOrderCouponHtml(url, daili);

            //if (string.IsNullOrEmpty(daili))
            //{
            //    Msg(msg, true);
            //}
            //BrowserGoodId browserGoodId =  new BrowserGoodId(url, tokens.ToList()[3]);
            //browserGoodId.ShowDialog();
        }

         async Task<string> GetTransacOrderCouponHtml(string url, string daili)
        {
            var restclient = RestClientUtil.CreateRestClient(url);

            restclient.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36";

            restclient.Proxy = RestClientUtil.CreateWebProxy(daili);

            var request = new RestRequest(Method.GET);
            //request.AddHeader("Content-Type", "application/json;charset=UTF-8");
            request.AddHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            //request.AddHeader("Host", "mobile.yangkeduo.com");
            request.AddHeader("Referer", url);
            //request.AddCookie("pdd_user_id", pddToken.pdd_user_id);
            //request.AddCookie("PDDAccessToken", pddToken.PDDAccessToken);

            var res = await restclient.ExecuteAsync(request);
            if (res.StatusCode == HttpStatusCode.OK)
            {
                return res.Content;
            }
            return "";
        }

        public static int GenerateRandomSeed()
        {
            return Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
        }

        private void uiButton3_Click_2(object sender, EventArgs e)
        {
            string nickName = "";
            string path = AppDomain.CurrentDomain.BaseDirectory + "昵称.txt";

            if (File.Exists(path))
            {
                Msg("使用自定义昵称库");
                var liens = File.ReadAllLines(path);
                if (liens.Length > 0)
                {
                    Random random = new Random(Guid.NewGuid().GetHashCode());
                    nickName = liens[random.Next(0, liens.Length)];
                }


            }

            if (string.IsNullOrWhiteSpace(nickName))
            {
                Msg("昵称获取失败，使用内置库");
                nickName = RandomName.GetNickName();
            }

            Msg("修改昵称：" + nickName);
        }

        private void MainPage_Initialize(object sender, EventArgs e)
        {

        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            if (!PuTongRadioButton.Checked) 
            {
                Msg("只支持普通模式",true);
                return;
            }
            string url = "http://mobile.yangkeduo.com/goods.html?goods_id=" + GetGoodId();
            BrowserNewFrom browserNewFrom = new BrowserNewFrom(url, AccountPddToken,PddGoodSource.PuTong);
            browserNewFrom.UpdateGoodInfoAction = UpdateGoodInfo;
            browserNewFrom.SetGoodIdAction = SetGoodId;
            browserNewFrom.ShowDialog();
        }

        private void uiButton3_Click_3(object sender, EventArgs e)
        {
            if (pddAddressDBModelList.Count() == 0)
            {
                Msg("地址为空，请添加地址再下单", true);
            }
            for (int i = 0; i < 10; i++)
            {
                PddAddressDBModel pddAddressDBModel = new PddAddressDBModel();
                PddAddress pddAddress = GetRandomAddress(this.RandomAddressCheckBox.Checked, ref pddAddressDBModel);
                Msg(pddAddressDBModel.address);
            }
         
        }
    }
}
 